package com.shinhye.wisdompeking.pager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.shinhye.wisdompeking.ConstantParams;
import com.shinhye.wisdompeking.NewsDetailActivity;
import com.shinhye.wisdompeking.R;
import com.shinhye.wisdompeking.base.BaseDataAdapter;
import com.shinhye.wisdompeking.base.BasePager;
import com.shinhye.wisdompeking.bean.NewsBean;
import com.shinhye.wisdompeking.bean.NewsBean.News;
import com.shinhye.wisdompeking.bean.NewsBean.Topnews;
import com.shinhye.wisdompeking.custom.AutoRollViewPager;
import com.shinhye.wisdompeking.custom.AutoRollViewPager.OnPagerClick;
import com.shinhye.wisdompeking.custom.pullrefreshview.PullToRefreshBase;
import com.shinhye.wisdompeking.custom.pullrefreshview.PullToRefreshBase.OnRefreshListener;
import com.shinhye.wisdompeking.custom.pullrefreshview.PullToRefreshListView;
import com.shinhye.wisdompeking.utils.SharedUtils;

public class NewsItemPager extends BasePager {
	private static final String TAG = "NewsItemPager";
	private static final String READ_IDS = "readIds";
	
	private LinearLayout top_news_viewpager;
	private TextView top_news_title;
	private LinearLayout dots_ll;
	private PullToRefreshListView lv_item_news;
	private String dataurl;
	private List<String> imgurls = new ArrayList<String>();
	private List<String> titles = new ArrayList<String>();
	private View roll_view;
	private RefreshableAdapter adapter;
	private List<News> news = new ArrayList<News>();
	private BitmapUtils bitmapUtils;
	private AutoRollViewPager vp_headimg;
	private String moreurl;
	private String readIds;

	public NewsItemPager(Context context, String dataurl) {
		super(context);
		this.dataurl = dataurl;
		Log.i(TAG, dataurl);
		
		bitmapUtils = new BitmapUtils(context);
		vp_headimg = new AutoRollViewPager(context, new OnPagerClick() {
			@Override
			public void onClick(int position) {
				Toast.makeText(NewsItemPager.this.context, titles.get(position), Toast.LENGTH_SHORT).show();
			}
		});
	}

	@Override
	public View initView() {
		roll_view = View.inflate(context, R.layout.layout_roll_view, null);
		top_news_viewpager = (LinearLayout) roll_view.findViewById(R.id.top_news_viewpager);
		top_news_title = (TextView) roll_view.findViewById(R.id.top_news_title);
		dots_ll = (LinearLayout) roll_view.findViewById(R.id.dots_ll);

		view = View.inflate(context, R.layout.frag_item_news, null);
		lv_item_news = (PullToRefreshListView) view.findViewById(R.id.lv_item_news);
		lv_item_news.setScrollLoadEnabled(true); //自动滚动加载
		lv_item_news.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				Log.i(TAG, "下拉刷新");
				obtainNetData(dataurl, true);
				
				String timeStamp = new SimpleDateFormat("MM/dd hh:mm").format(new Date());
				lv_item_news.getHeaderLoadingLayout().setLastUpdatedLabel(timeStamp);
			}
			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				Log.i(TAG, "上拉加载");
				obtainNetData(moreurl, false);
			}
		});
		lv_item_news.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//读过的新闻id存储形式：#2113#32111#8923#
				if(!readIds.contains("#" + news.get(position - 1).id + "#")) {
					readIds += news.get(position - 1).id + "#";
					SharedUtils.putString(context, READ_IDS, readIds);
					adapter.notifyDataSetChanged();
				}
				
				Intent intent = new Intent(context, NewsDetailActivity.class);
				intent.putExtra("newsurl", news.get(position - 1).url);
				intent.putExtra("newstitle", news.get(position - 1).title);
				context.startActivity(intent);
			}
		});
		
		return view;
	}

	@Override
	public void initData() {
		readIds = SharedUtils.getString(context, READ_IDS, "#");
		String result = SharedUtils.getString(context, ConstantParams.BASE_URL + dataurl, "");
		if(TextUtils.isEmpty(result)) {
			obtainNetData(dataurl, true);
		} else {
			Log.i(TAG, "本地获取了");
			setData(result, true);
		}
	}

	/**
	 * 从网络获取数据
	 * @param url 地址
	 * @param isRefresh 是否为下拉刷新
	 */
	private void obtainNetData(final String url, final boolean isRefresh) {
		Log.i(TAG, "网络获取了");
		if(!TextUtils.isEmpty(url)) {
			HttpUtils httpUtils = new HttpUtils();
			httpUtils.send(HttpMethod.POST, ConstantParams.BASE_URL + url, new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					SharedUtils.putString(context, ConstantParams.BASE_URL + url, responseInfo.result);
					setData(responseInfo.result, isRefresh);
				}
				@Override
				public void onFailure(HttpException error, String msg) {}
			});
		} else {
			Toast.makeText(context, "没有更多数据了！", Toast.LENGTH_SHORT).show();
			lv_item_news.onPullUpRefreshComplete();
			lv_item_news.onPullDownRefreshComplete();
		}
	}

	private void setData(String result, boolean isRefresh) {
		Gson gson = new Gson();
		NewsBean newsbean = gson.fromJson(result, NewsBean.class);
		if("200".equals(newsbean.retcode)) {
			moreurl = newsbean.data.more;
			
			List<Topnews> topnews = newsbean.data.topnews;
			if(topnews.size() > 0) {
				//刷新时才重新显示头条
				if(isRefresh) {
					imgurls.clear();
					for (Topnews topnew : topnews) {
						imgurls.add(topnew.topimage);
						titles.add(topnew.title);
					}
					
					vp_headimg.setImageUrl(imgurls);
					vp_headimg.attachDotGroup(dots_ll);
					vp_headimg.attachTitle(top_news_title, titles);
					vp_headimg.startRoll();
					
					top_news_viewpager.removeAllViews();
					top_news_viewpager.addView(vp_headimg);
					if(lv_item_news.getRefreshableView().getHeaderViewsCount() < 1) {
						lv_item_news.getRefreshableView().addHeaderView(roll_view);
					}
				}
			} else {
				//没有头条新闻信息
			}
			
			if(newsbean.data.news.size() > 0) {
				//刷新时才重新显示新闻条目
				if(isRefresh) {
					news.clear();
				}
				news.addAll(newsbean.data.news);
			} else {
				//没有新闻信息
			}
			
			if(adapter == null) {
				adapter = new RefreshableAdapter(context, news);
				lv_item_news.getRefreshableView().setAdapter(adapter);
			} else {
				adapter.notifyDataSetChanged();
			}
			
			lv_item_news.onPullUpRefreshComplete();
			lv_item_news.onPullDownRefreshComplete();
		}
	}
	
	private class RefreshableAdapter extends BaseDataAdapter<News> {
		public RefreshableAdapter(Context context, List<News> list) {
			super(context, list);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				convertView = View.inflate(context, R.layout.layout_news_item, null);
				ViewHolder holder = new ViewHolder();
				holder.iv_img = (ImageView) convertView.findViewById(R.id.iv_img);
				holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
				holder.tv_pub_date = (TextView) convertView.findViewById(R.id.tv_pub_date);
				holder.tv_comment_count = (TextView) convertView.findViewById(R.id.tv_comment_count);
				convertView.setTag(holder);
			}
			ViewHolder holder = (ViewHolder) convertView.getTag();
			News newz = news.get(position);
			bitmapUtils.display(holder.iv_img, newz.listimage);
			holder.tv_title.setText(newz.title);
			holder.tv_pub_date.setText(newz.pubdate);
			holder.tv_comment_count.setText(new Random().nextInt(1000) + "");
			
			if(readIds.contains("#" + news.get(position).id + "#")){
				holder.tv_title.setTextColor(context.getResources().getColor(R.color.news_item_has_read_textcolor));
			}else{
				holder.tv_title.setTextColor(context.getResources().getColor(R.color.news_item_no_read_textcolor));
			}
			
			return convertView;
		}
	}
	
	class ViewHolder {
		ImageView iv_img;
		TextView tv_title;
		TextView tv_pub_date;
		TextView tv_comment_count;
	}
}
